/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import quanlyduongsat.MainProgram;

/**
 *
 * @author Phong
 */
public class BackupGUI extends javax.swing.JPanel {

    /**
     * Creates new form BackupGUI
     */
    public BackupGUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtPath = new javax.swing.JTextField();
        btnBackup = new javax.swing.JButton();
        btnBrowse = new javax.swing.JButton();
        lblMessage = new javax.swing.JLabel();

        txtPath.setEditable(false);

        btnBackup.setIcon(new javax.swing.ImageIcon("C:\\Users\\PC\\Downloads\\java-quanlyduongsat\\java-quanlyduongsat\\src\\Images\\backup.png")); // NOI18N
        btnBackup.setText("Create Backup");
        btnBackup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackupActionPerformed(evt);
            }
        });

        btnBrowse.setBackground(new java.awt.Color(0, 0, 0));
        btnBrowse.setForeground(new java.awt.Color(0, 255, 153));
        btnBrowse.setText("Browse");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(135, Short.MAX_VALUE)
                .addComponent(lblMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(308, 308, 308))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(6, 6, 6)
                    .addComponent(txtPath)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnBrowse)
                    .addGap(7, 7, 7)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(186, 186, 186)
                .addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addGap(88, 88, 88))
            .addGroup(layout.createSequentialGroup()
                .addGap(164, 164, 164)
                .addComponent(btnBackup)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(118, 118, 118)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnBrowse))
                    .addContainerGap(294, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents
  static int BUFFER = 10485760;
    public static String getData(String host, String port, String user, String password, String db) throws Exception {
        Process run = Runtime.getRuntime().exec(
                "C:\\wamp\\bin\\mysql\\mysql5.6.12\\bin\\mysqldump --host=" + host + " --port=" + port
                + " --user=" + user + " --password=" + password
                + " --compact --databases --add-drop-table --complete-insert --extended-insert "
                + "--skip-comments --skip-triggers " + db);
        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer temp = new StringBuffer();
        int count;
        char[] cbuf = new char[BUFFER];

        while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
            temp.append(cbuf, 0, count);
        }
        br.close();
        in.close();

        return temp.toString();
    }
    private void btnBackupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackupActionPerformed
        if (txtPath.getText().equals("")) {
            lblMessage.setText("<html><font color='red'>Please choose path to save!</font></html>");
        } else {
            try {
            byte[] data = getData("localhost", "3306", "root", "", "quanlyduongsat").getBytes();
            File filedst = new File(Path);
            FileOutputStream dest;
            dest = new FileOutputStream(filedst);
            dest.write(data);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Sao Lưu Dữ Liệu Không Thành Công");
        } catch (IOException ex) {
            Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Sao Lưu Dữ Liệu Không Thành Công");
        } catch (URISyntaxException ex) {
            Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Sao Lưu Dữ Liệu Không Thành Công");
        } catch (Exception ex) {
            Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Sao Lưu Dữ Liệu Không Thành Công");
        }
        JOptionPane.showMessageDialog(null, "Sao Lưu Dữ Liệu Thành Công");
    }//GEN-LAST:event_btnBackupActionPerformed
    }
     String Path = "";
    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed

          
        try {
            JFileChooser fc = new JFileChooser(Path);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Backup", "sql");
            fc.setFileFilter(filter);
            fc.setSelectedFile(new File("QuanLyDuongSat.sql"));
            int returnVal = fc.showSaveDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                Path = file.getPath();
                txtPath.setText(Path);
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnBrowseActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBackup;
    private javax.swing.JButton btnBrowse;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JTextField txtPath;
    // End of variables declaration//GEN-END:variables
}
